﻿namespace DimensionsHelper.Client.WinUi.Models;

public class ProjectTaskProgressEnumerator<T>(
    MessageModel model,
    IEnumerable<T> source,
    int length,
    Func<T, double, string>? messageGetter)
    : IEnumerator<T>
{
    private int _index;
    private IEnumerator<T> _inner = source.GetEnumerator();

    private Func<T, double, string>? MessageGetter
    {
        get;
    } = messageGetter;

    public T Current => _inner.Current;

    object IEnumerator.Current => Current!;

    public bool MoveNext()
    {
        if (!_inner.MoveNext())
        {
            return false;
        }

        _index++;
        double per = _index / (double)length * 100;
        string message = MessageGetter == null ? $"{_index} / {length}, Per: {per}%" : MessageGetter(Current, per);

        App.DispatcherQueue.TryEnqueue(() =>
        {
            model.Message = message;
            model.Progress = per;
        });

        return true;
    }

    public void Reset()
    {
        _inner = source.GetEnumerator();
        _index = 0;
    }

    public void Dispose()
    {
        _inner.Dispose();
        GC.SuppressFinalize(this);
    }
}

public class ProjectTaskProgressEnumerable<T>(
    MessageModel model,
    IEnumerable<T> source,
    int length,
    Func<T, double, string>? messageGetter)
    : IProgressEnumerable<T>
{
    public Func<T, double, string>? MessageGetter { get; } = messageGetter;

    public IEnumerator<T> GetEnumerator() =>
        new ProjectTaskProgressEnumerator<T>(model, source, length, MessageGetter);

    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}